package com.taskschecker;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.taskschecker.db.DBManager;
import com.taskschecker.db.TaskGroup;
import com.taskschecker.db.TaskInfo;

public class TaskGroupEditActivity extends Activity {
	private DBManager mgr;
	private EditText startDate;
	private EditText endDate;
	private EditText contentText;
	private EditText memoText;
	private Button btnEditSave;
	private RadioButton radioButtonDaily;
	private RadioButton radioButtonPerWeek;
	private RadioButton radioButtonPerMonth;
	private LinearLayout weekLayout;
	private LinearLayout monthLayout;
	private RadioGroup repeatGroup;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int timeFlag;
	private String groupId;
	private List<CheckBox> weekList = new ArrayList<CheckBox>();
	private List<CheckBox> dayList = new ArrayList<CheckBox>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_group_edit);

		mgr = new DBManager(this);

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int screenWidth = metric.widthPixels;
		LinearLayout.LayoutParams layout_params = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		layout_params.width = screenWidth / 2 - 20;
		groupId = getIntent().getStringExtra("groupId");
		TaskGroup taskgroup = mgr.getTaskGroupById(groupId);

		startDate = (EditText) findViewById(R.id.EditText_StartDate_edit);
		startDate.setLayoutParams(layout_params);
		String tempStr = (Integer.toString(taskgroup.getStartdate()));
		startDate.setText(tempStr.substring(0, 4) + "-"
				+ tempStr.substring(4, 6) + "-" + tempStr.substring(6, 8));
		startDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				timeFlag = 0;
				mYear = Integer.parseInt(startDate.getText().toString()
						.split("-")[0]);
				mMonth = Integer.parseInt(startDate.getText().toString()
						.split("-")[1]) - 1;
				mDay = Integer.parseInt(startDate.getText().toString()
						.split("-")[2]);
				showDialog(0);
			}
		});
		startDate.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus == true) {
					timeFlag = 0;
					mYear = Integer.parseInt(startDate.getText().toString()
							.split("-")[0]);
					mMonth = Integer.parseInt(startDate.getText().toString()
							.split("-")[1]) - 1;
					mDay = Integer.parseInt(startDate.getText().toString()
							.split("-")[2]);
					showDialog(0);
				}
			}
		});

		endDate = (EditText) findViewById(R.id.EditText_EndDate_edit);
		endDate.setLayoutParams(layout_params);
		tempStr = (Integer.toString(taskgroup.getEnddate()));
		endDate.setText(tempStr.substring(0, 4) + "-" + tempStr.substring(4, 6)
				+ "-" + tempStr.substring(6, 8));
		endDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				timeFlag = 1;
				mYear = Integer.parseInt(endDate.getText().toString()
						.split("-")[0]);
				mMonth = Integer.parseInt(endDate.getText().toString()
						.split("-")[1]) - 1;
				mDay = Integer
						.parseInt(endDate.getText().toString().split("-")[2]);
				showDialog(1);
			}
		});
		endDate.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus == true) {
					timeFlag = 1;
					mYear = Integer.parseInt(endDate.getText().toString()
							.split("-")[0]);
					mMonth = Integer.parseInt(endDate.getText().toString()
							.split("-")[1]) - 1;
					mDay = Integer.parseInt(endDate.getText().toString()
							.split("-")[2]);
					showDialog(1);
				}
			}
		});

		contentText = (EditText) findViewById(R.id.EditText_Content_edit);
		contentText.setText(taskgroup.getContent());

		memoText = (EditText) findViewById(R.id.EditText_Memo_edit);
		memoText.setText(taskgroup.getMemo());

		btnEditSave = (Button) findViewById(R.id.Button_EditSave);

		weekLayout = (LinearLayout) findViewById(R.id.weekLayout_edit);
		monthLayout = (LinearLayout) findViewById(R.id.monthLayout_edit);

		repeatGroup = (RadioGroup) findViewById(R.id.repeatGroup_edit);

		radioButtonDaily = (RadioButton) findViewById(R.id.ataaw1_edit);
		radioButtonPerWeek = (RadioButton) findViewById(R.id.ataaw2_edit);
		radioButtonPerMonth = (RadioButton) findViewById(R.id.ataaw3_edit);

		creatWeekList();
		creatDayList();
		if (taskgroup.getRepeatetype() == 0) {
			radioButtonDaily.setChecked(true);
		} else if (taskgroup.getRepeatetype() == 1) {
			radioButtonPerWeek.setChecked(true);
			weekLayout.setVisibility(View.VISIBLE);
			String tmpRepeateValue = taskgroup.getRepeatevalue();
			if (!"".equals(tmpRepeateValue)) {
				String[] sourceStrArray = tmpRepeateValue.split(",");
				for (int i = 0; i < sourceStrArray.length; i++) {
					weekList.get(Integer.parseInt(sourceStrArray[i]) - 1)
							.setChecked(true);
				}
			}

		} else if (taskgroup.getRepeatetype() == 2) {
			radioButtonPerMonth.setChecked(true);
			monthLayout.setVisibility(View.VISIBLE);
			String tmpRepeateValue = taskgroup.getRepeatevalue();
			if (!"".equals(tmpRepeateValue)) {
				String[] sourceStrArray = tmpRepeateValue.split(",");
				for (int i = 0; i < sourceStrArray.length; i++) {
					dayList.get(Integer.parseInt(sourceStrArray[i]) - 1)
							.setChecked(true);
				}
			}

		}

		mYear = CalendarUtils.getCurrentDateSplit().get("YEAR");
		mMonth = CalendarUtils.getCurrentDateSplit().get("MONTH");
		mDay = CalendarUtils.getCurrentDateSplit().get("DAY");

		btnEditSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (checkData(
						contentText.getText().toString(),
						Integer.valueOf(startDate.getText().toString()
								.replace("-", "")),
						Integer.valueOf(endDate.getText().toString()
								.replace("-", "")))) {
					TaskGroup taskgroup = new TaskGroup();
					List<TaskInfo> taskinfoList = new ArrayList<TaskInfo>();
					taskgroup.setTaskgroupid(Integer.parseInt(groupId));
					taskgroup.setContent(contentText.getText().toString());
					taskgroup.setStartdate(Integer.valueOf(startDate.getText()
							.toString().replace("-", "")));
					taskgroup.setEnddate(Integer.valueOf(endDate.getText()
							.toString().replace("-", "")));
					taskgroup.setMemo(memoText.getText().toString());
					List<String> dateList = getDateStrOfDayRepeat(startDate
							.getText().toString(), endDate.getText().toString());
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

					if (repeatGroup.getCheckedRadioButtonId() == radioButtonDaily
							.getId()) {
						taskgroup.setRepeatetype(0);
						taskgroup.setRepeatevalue("");
						for (String tempDate : dateList) {
							if (Integer.valueOf(tempDate.replace("-", "")) >= CalendarUtils
									.getCurrentDateInt()) {
								TaskInfo taskinfo = new TaskInfo();
								taskinfo.setContent(taskgroup.getContent());
								taskinfo.setDate(Integer.valueOf(tempDate
										.replace("-", "")));
								taskinfo.setMemo(taskgroup.getMemo());
								taskinfo.setCompleteness(0);
								taskinfo.setGroupid(Integer.parseInt(groupId));
								taskinfoList.add(taskinfo);
							}

						}
					} else if (repeatGroup.getCheckedRadioButtonId() == radioButtonPerWeek
							.getId()) {
						taskgroup.setRepeatetype(1);
						String weekStr = "";
						int i = 1;
						for (CheckBox cb : weekList) {
							if (cb.isChecked()) {
								if (weekStr.equals("")) {
									weekStr = Integer.toString(i);
								} else {
									weekStr += "," + Integer.toString(i);
								}
							}
							i++;
						}
						taskgroup.setRepeatevalue(weekStr);
						Calendar tempCalendar = new GregorianCalendar();
						Date tempDay = null;
						for (String tempDate : dateList) {
							try {
								tempDay = df.parse(tempDate);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							tempCalendar.setTime(tempDay);
							int dayOfWeek = tempCalendar
									.get(Calendar.DAY_OF_WEEK);
							if (weekStr.indexOf(Integer.toString(dayOfWeek)) > -1) {
								if (Integer.valueOf(tempDate.replace("-", "")) >= CalendarUtils
										.getCurrentDateInt()) {
									TaskInfo taskinfo = new TaskInfo();
									taskinfo.setContent(taskgroup.getContent());
									taskinfo.setDate(Integer.valueOf(tempDate
											.replace("-", "")));
									taskinfo.setMemo(taskgroup.getMemo());
									taskinfo.setCompleteness(0);
									taskinfo.setGroupid(Integer
											.parseInt(groupId));
									taskinfoList.add(taskinfo);
								}
							}
						}
					} else if (repeatGroup.getCheckedRadioButtonId() == radioButtonPerMonth
							.getId()) {
						taskgroup.setRepeatetype(2);
						String dayStr = "";
						int i = 1;
						for (CheckBox cb : dayList) {
							if (cb.isChecked()) {
								if (dayStr.equals("")) {
									dayStr = Integer.toString(i);
								} else {
									dayStr += "," + Integer.toString(i);
								}
							}
							i++;
						}
						taskgroup.setRepeatevalue(dayStr);

						Calendar tempCalendar = new GregorianCalendar();
						Date tempDay = null;
						for (String tempDate : dateList) {
							try {
								tempDay = df.parse(tempDate);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							tempCalendar.setTime(tempDay);
							int dayOfMonth = tempCalendar
									.get(Calendar.DAY_OF_MONTH);
							if (("," + dayStr + ",").indexOf((","
									+ Integer.toString(dayOfMonth) + ",")) > -1) {
								if (Integer.valueOf(tempDate.replace("-", "")) >= CalendarUtils
										.getCurrentDateInt()) {
									TaskInfo taskinfo = new TaskInfo();
									taskinfo.setContent(taskgroup.getContent());
									taskinfo.setDate(Integer.valueOf(tempDate
											.replace("-", "")));
									taskinfo.setMemo(taskgroup.getMemo());
									taskinfo.setCompleteness(0);
									taskinfo.setGroupid(Integer
											.parseInt(groupId));
									taskinfoList.add(taskinfo);
								}
							}
						}
					}
					mgr.updateTaskGroupAndAddTaskInfo(taskgroup, CalendarUtils
							.getCurrentDateInt().toString(), taskinfoList);
					sendUpdateWidgetBroadcast();
					finish();

				}

			}
		});

		repeatGroup
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						if (checkedId == radioButtonDaily.getId()) {
							weekLayout.setVisibility(View.GONE);
							monthLayout.setVisibility(View.GONE);
						} else if (checkedId == radioButtonPerWeek.getId()) {
							weekLayout.setVisibility(View.VISIBLE);
							monthLayout.setVisibility(View.GONE);
						} else if (checkedId == radioButtonPerMonth.getId()) {
							weekLayout.setVisibility(View.GONE);
							monthLayout.setVisibility(View.VISIBLE);
						}
					}
				});

	}

	private boolean checkData(String content, Integer startDate, Integer endDate) {
		if ("".equals(content)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					TaskGroupEditActivity.this);
			builder.setMessage(getResources().getString(
					R.string.message_check_content));
			builder.setPositiveButton("OK", null);
			builder.show();
			return false;
		} else if (startDate > endDate) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					TaskGroupEditActivity.this);
			builder.setMessage(getResources().getString(
					R.string.message_check_date));
			builder.setPositiveButton("OK", null);
			builder.show();
			return false;
		} else {
			return true;
		}
	}

	@SuppressLint("SimpleDateFormat")
	private List<String> getDateStrOfDayRepeat(String startDate, String endDate) {
		List<String> dateList = new ArrayList<String>();

		Calendar calStart = new GregorianCalendar();
		Calendar calEnd = new GregorianCalendar();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date dayStart = null;
		Date dayEnd = null;
		try {
			dayStart = df.parse(startDate);
			dayEnd = df.parse(endDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		calStart.setTime(dayStart);
		calEnd.setTime(dayEnd);
		for (; calStart.compareTo(calEnd) <= 0;) {
			dateList.add(df.format(calStart.getTime()));
			calStart.add(Calendar.DAY_OF_YEAR, 1);
		}
		return dateList;
	}

	private void creatWeekList() {
		weekList.add((CheckBox) findViewById(R.id.checkBox_week1_edit));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week2_edit));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week3_edit));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week4_edit));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week5_edit));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week6_edit));
		weekList.add((CheckBox) findViewById(R.id.checkBox_week7_edit));
	}

	private void creatDayList() {
		dayList.add((CheckBox) findViewById(R.id.checkBox_day1_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day2_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day3_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day4_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day5_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day6_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day7_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day8_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day9_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day10_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day11_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day12_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day13_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day14_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day15_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day16_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day17_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day18_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day19_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day20_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day21_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day22_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day23_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day24_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day25_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day26_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day27_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day28_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day29_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day30_edit));
		dayList.add((CheckBox) findViewById(R.id.checkBox_day31_edit));
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			String mm;
			String dd;
			if (monthOfYear < 9) {
				mm = "0" + (monthOfYear + 1);
			} else {
				mm = String.valueOf(monthOfYear + 1);
			}
			if (dayOfMonth <= 9) {
				dd = "0" + dayOfMonth;
			} else {
				dd = String.valueOf(dayOfMonth);
			}
			if (timeFlag == 0) {
				startDate.setText(String.valueOf(year) + "-" + mm + "-" + dd);
			} else {
				endDate.setText(String.valueOf(year) + "-" + mm + "-" + dd);
			}
		}
	};

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case 1:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	public void sendUpdateWidgetBroadcast() {
		Intent intent = new Intent();
		intent.setAction("cmn.taskschecker.widget.update");
		getApplicationContext().sendBroadcast(intent);
	}
}
